package person.drf.shop.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import person.drf.common.constant.ProductConstant;
import person.drf.common.to.SkuHasStockVo;
import person.drf.common.to.SkuReductionTo;
import person.drf.common.to.SpuBoundTo;
import person.drf.common.to.es.SkuEsModel;
import person.drf.common.utils.PageUtils;
import person.drf.common.utils.Query;

import person.drf.common.utils.R;
import person.drf.shop.product.dao.SpuInfoDao;
import person.drf.shop.product.entity.*;
import person.drf.shop.product.feign.CouponFeignService;
import person.drf.shop.product.feign.SearchFeignService;
import person.drf.shop.product.feign.WareFeignService;
import person.drf.shop.product.service.*;
import person.drf.shop.product.vo.*;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    AttrService attrService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        //1.保存spu基本信息 pms_spu_info
        SpuInfoEntity infoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo,infoEntity);
        infoEntity.setCreateTime(new Date());
        infoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(infoEntity);

        //2.保存spu的描述图片 pms_spu_info_desc
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(infoEntity.getId());  //使用刚刚保存的spu类的id
        descEntity.setDecript(String.join(",",decript));  //使用逗号分隔，把集合写成字符串
        spuInfoDescService.saveSpuInfoDesc(descEntity);

        //3.保存spu的图片集 pms_spu_images
        List<String> images = vo.getImages();

        spuImagesService.saveImages(infoEntity.getId(),images);

        //4.保存spu的规格参数  pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setSpuId(infoEntity.getId()); //spuid
            valueEntity.setAttrId(attr.getAttrId()); //基本属性id
            AttrEntity byId = attrService.getById(attr.getAttrId());
            valueEntity.setAttrName(byId.getAttrName());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc());

            return valueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(collect);

        //5、保存spu的积分信息；gulimall_sms->sms_spu_bounds
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(infoEntity.getId());
        couponFeignService.saveSpuBounds(spuBoundTo);

        //6.保存当前spu对应的所有sku信息
        // 6.1)  sku基本信息 pms_sku_info
        List<Skus> skus = vo.getSkus();
        if(skus!=null && skus.size()>0){
           skus.forEach(item ->{
               //获取sku默认图片  可能会没有
               String defaultImage = "";
               for(Images img: item.getImages()){
                   if(img.getDefaultImg() == 1){
                       defaultImage = img.getImgUrl();
                   }
               }
               SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
               BeanUtils.copyProperties(item,skuInfoEntity);
               //某些没有的属性我们需要自己来赋值
               skuInfoEntity.setSkuDefaultImg(defaultImage);
               skuInfoEntity.setBrandId(infoEntity.getBrandId());
               skuInfoEntity.setCatalogId(infoEntity.getCatalogId());
               skuInfoEntity.setSpuId(infoEntity.getId());
               skuInfoEntity.setSaleCount(0L);
               skuInfoService.saveSkuInfo(skuInfoEntity);

               // 6.2)  保存sku所有图片信息 pms_sku_images
               Long skuId = skuInfoEntity.getSkuId();
               List<SkuImagesEntity> collect1 = item.getImages().stream().map(img -> {
                   SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                   skuImagesEntity.setSkuId(skuId);
                   skuImagesEntity.setImgUrl(img.getImgUrl());
                   skuImagesEntity.setDefaultImg(img.getDefaultImg());
                   return skuImagesEntity;
               }).filter(entity ->{
                   //因为spu可能并不需要 spu提供的全部图片，所以剔除不需要的
                   //返回true就是需要 false就是剔除
                   return !StringUtils.isEmpty(entity.getImgUrl());
               }).collect(Collectors.toList());
               skuImagesService.saveBatch(collect1);

               // 6.3)  sku销售属性信息 pms_sku_sale_attr_value
               List<Attr> attrs = item.getAttr();
               List<SkuSaleAttrValueEntity> collect2 = attrs.stream().map(a -> {
                   SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                   BeanUtils.copyProperties(a, attrValueEntity);
                   attrValueEntity.setSkuId(skuId);
                   return attrValueEntity;
               }).collect(Collectors.toList());
               skuSaleAttrValueService.saveBatch(collect2);

               // 6.4）sku的优惠、满减等信息；gulimall_sms->sms_sku_ladder\sms_sku_full_reduction\sms_member_price
               SkuReductionTo skuReductionTo = new SkuReductionTo();
               BeanUtils.copyProperties(item,skuReductionTo);
               skuReductionTo.setSkuId(skuId);
               if(skuReductionTo.getFullCount()>0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0"))==1){
                   couponFeignService.saveSkuReduction(skuReductionTo);
               }

           });
        }

    }

    //保存spu基本信息
    @Override
    public void saveBaseSpuInfo(SpuInfoEntity infoEntity) {
        this.baseMapper.insert(infoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper();
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            queryWrapper.and((w)->{
                w.eq("id",key).or().like("spu_name",key);
            });
        }
        String status = (String) params.get("status");
        if(!StringUtils.isEmpty(status)){
            queryWrapper.eq("publish_status",status);
        }
        //不为空  同时不为0  才拼接
        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            queryWrapper.eq("brand_id",brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId)  && !"0".equalsIgnoreCase(catelogId)){
            queryWrapper.eq("catalog_id",catelogId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    @Override
    public void spuUp(Long spuid) {
        // 1.组装需要的数据
        // 1.1查出当前spu对应的所有sku信息
        List<SkuInfoEntity> skus = skuInfoService.getSkuBySpuId(spuid);

        // 1.2 esModel中的hasStock（是否有库存）
        //发送远程调用  查询是否有库存
        Map<Long, Boolean> stockMap = null;
        try {
            List<Long> skuIdList = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
            R skusHasStock = wareFeignService.getSkusHasStock(skuIdList);
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {
            };
            stockMap = skusHasStock.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        } catch (Exception e) {
            log.error("库存服务调查异常,原因{}", e);
        }

        // 1.3 esModel中的List<Attrs>  当前sku的所有可以被检索的规格属性
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseAttrListforSpu(spuid);
        List<Long> attrIds = baseAttrs.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        List<Long> searchAttrIds = attrService.selectSearchAttrs(attrIds);  //指定所有属性集合里面 ，挑出可检索属性id
        Set<Long> idSet = new HashSet<>(searchAttrIds);
        List<SkuEsModel.Attrs> attrsList = baseAttrs.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs a = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, a);
            return a;
        }).collect(Collectors.toList());


        // 2.封装每个sku检索信息
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> upProducts = skus.stream().map(sku -> {

            SkuEsModel esModel = new SkuEsModel();
            //先把sku有的数据先封装
            BeanUtils.copyProperties(sku, esModel);
            //esModel在sku没有的数据
            // skuPrice skuImg
            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());
            // hotScore(热度评分先给0)
            esModel.setHotScore(0L);
            // hasStock->  发送远程调用库存系统，查询是否有库存
            if (finalStockMap == null) {
                esModel.setHasStock(true);
            } else {
                esModel.setHasStock(finalStockMap.get(sku.getSkuId()));
            }
            // catalogName brandName brandImage   ->查询品牌和分类信息
            esModel.setBrandName(brandService.getById(sku.getBrandId()).getName());
            esModel.setBrandImg(brandService.getById(sku.getBrandId()).getLogo());
            esModel.setCatalogName(categoryService.getById(sku.getCatalogId()).getName());
            // 设置属性 attrs
            esModel.setAttrs(attrsList);
            return esModel;
        }).collect(Collectors.toList());

        // 3. 发送数据给es保存
        searchFeignService.productStatusUp(upProducts);

        //修改spu状态
        this.baseMapper.updateSpuStatus(spuid, ProductConstant.StatusEnum.SPU_UP.getCode());

    }
}